-1

I work with canvas, and i have issues, i want to create layout with canvas objects. But i want to create object in css, and create in HTML.

For now i create:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.beginPath();


context.rect(10, 50, 200, 100);
context.fillStyle = 'red';
context.fill();
context.fillStyle = 'black';
context.font = '20px Courier';
context.shadowColor = 'transparent';
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.fillText(`List item`, 70, 80);
context.fillText(`List item2`, 70, 130);

var image = new Image();
image.src = "https://pngimage.net/wp-content/uploads/2018/06/machine-icon-png-9.png";
image.onload = function () {
    context.drawImage(image, 10, 70, 50, 50);
};

CSS:

.box-test {
    width: 150px;
    height: 100px;
    background-color: #fff;
}

HTML:

 <canvas id="myCanvas" width="1280" height="720"
            style="border:1px solid #c3c3c3;">
        Your browser does not support the canvas element.
    </canvas>

This code are build boxes with image and text, but color, image i want to get from CSS, somehow it's possible to create object in canvas use css styles?

As u can see i have class box-test and here i give properties to box:

context.rect(10, 50, 200, 100);
    context.fillStyle = 'red';
    context.fill();

Can i use only cordinates here, and width, height, color get from css?

Andrew
  • 372
  • 2
  • 5
  • 25

1 Answers1

-1

If you use SVG you can on the fly add elements to it

var canvas = document.getElementById("svgArea");
var rec = document.createElementNS("http://www.w3.org/2000/svg","rect")
rec.setAttributeNS(null, "class","box-test");
canvas.appendChild(rec);

var image = document.createElementNS("http://www.w3.org/2000/svg","image")
image.setAttributeNS(null, "href","https://pngimage.net/wp-content/uploads/2018/06/machine-icon-png-9.png");
image.setAttributeNS(null, 'height', '50');
image.setAttributeNS(null, 'width', '50');
image.setAttributeNS(null, 'x', 60);
image.setAttributeNS(null, 'y', 60); 
canvas.appendChild(image );

var text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent= "Hello World!";
text.setAttributeNS(null, 'x', 120);
text.setAttributeNS(null, 'y', 120); 
text.setAttributeNS(null, "class","text-style");
canvas.appendChild(text);
.box-test {
    width: 50px;
    height: 50px;
 x: 20px;
 y: 20px;
    fill:rgb(0,0,255);
    stroke-width:3;
    stroke:rgb(0,0,0);
}

.text-style {
    font-size: 20px;
    font-family: Courier;
}
<svg id="svgArea" width="500" height="500"></svg>

To set X and Y coordinates then you can use this code

rec.setAttributeNS(null, 'x', x);
rec.setAttributeNS(null, 'y', y);

To set width and height

rec.setAttributeNS(null, 'height', '50');
rec.setAttributeNS(null, 'width', '50'); 
Dickens A S
  • 3,824
  • 2
  • 22
  • 45