如何在画布对象jQuery中添加类



我使用画布,我有问题,我想用画布对象创建布局。但我想用css创建对象,用HTML创建。

现在我创建:

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>

这段代码是用图像和文本构建的盒子,但我想从CSS中获得颜色、图像,不知何故,在画布中使用CSS样式创建对象是可能的?

正如你所看到的,我有一个类的box测试,在这里我给出了box的属性:

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

我可以在这里只使用堇青石吗?并且宽度、高度、颜色可以从css获得吗?

如果您使用SVG,您可以随时向其添加元素

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>

要设置XY坐标,则可以使用此代码

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

设置widthheight

rec.setAttributeNS(null, 'height', '50');
rec.setAttributeNS(null, 'width', '50'); 

最新更新