Skip to content
Advertisement

how to create box in HTML5?

I am trying to create two inner box . I am able to do in using HTML css . working link (expected output) https://stackblitz.com/edit/js-lvzg4o?file=index.js enter image description here

When I trying to do the same thing using Canvas. I am not able create two box or container where I will put my text.

is it possible to do same thing using canvas

// Import stylesheets
import './style.css';
const post = {
  title: 'Draw and save images with Canvas and Node',
};
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.fillStyle = '#eee';
ctx.fillRect(10, 10, 150, 100);

ctx.font = 'bold 16px';
ctx.textAlign = 'center';
ctx.fillStyle = '#000';

ctx.fillText(post.title, 0, 93);

here is my code https://stackblitz.com/edit/js-6ameba?file=index.js

current output

Advertisement

Answer

Begin your drawing movements with ctx.beginPath()

In order for canvas to know when to start tracking movement, you need to invoke beginPath() on the 2d context. There is no need for two contexts.

Important note, Canvas is NOT html, You will need to do the math to calculate line wrapping yourself. There is a measureText(string) method that will provide you with the information based on font family and size.

// Import stylesheets

const post = {
  title: 'Draw and save images with Canvas and Node',
};

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.fillStyle = 'yellow';
ctx.fillRect(10, 10, 150, 100);

ctx.font = 'bold 16px';
// ctx.textAlign = 'center';
ctx.fillStyle = '#000';
ctx.fillText(post.title, 10, 93);

ctx.fillStyle = '#eee';
ctx.fillRect(10, 300, 150, 100);

//var size = ctx.measureText(post.title).width;

ctx.textAlign = 'left';
ctx.fillStyle = '#000';
   
ctx.fillText(post.title, 10, 380);
<canvas id="canvas" width="340" height="440"></canvas>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement