使用jquery创建canvas元素

时间:2017-02-05 11:28:08

标签: javascript jquery html5-canvas

我是jQuery的新手可以有人告诉如何做到这一点吗?

我在html代码之间执行此操作

<script>
var Canvas_width=400;
var Canvas_height=300;
var CanvasElement =$("<canvas width='" + Canvas_width + "'height='" + Canvas_height + "'></canvas>");
var canvas=CanvasElement.get(0).getContext("2d");

CanvasElement.appendTo('body');
canvas.fillStyle = "#000000";
canvas.fill();
</script>

2 个答案:

答案 0 :(得分:0)

在填充之前,您只需要创建一个与画布大小相同的矩形:

canvas.rect(0, 0, Canvas_width, Canvas_height);

<强>演示

&#13;
&#13;
var Canvas_width = 400;
var Canvas_height = 300;
var CanvasElement = $("<canvas width='" + Canvas_width + "' height='" + Canvas_height + "'></canvas>");
var canvas = CanvasElement.get(0).getContext("2d");

CanvasElement.appendTo('body');
canvas.rect(0, 0, Canvas_width, Canvas_height); // <======= HERE
canvas.fillStyle = "#000000";
canvas.fill();
&#13;
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是你应该怎么做的。 不要添加画布上下文,添加元素本身

var Canvas_width=400;
var Canvas_height=300;
var CanvasElement = $("<canvas width='" + Canvas_width + "'height='" + Canvas_height + "'></canvas>");
// Add the canvas element, not the context: CanvasElement[0].getContext('2d')
document.body.appendChild(CanvasElement[0]);

// Now create the canvas context, this is what you need to draw something
var canvasContext=CanvasElement[0].getContext("2d");
// call beginPath() before drawing on the canvas
canvasContext.beginPath();
// Select the rectangle inside your canvas in which you want to draw something
canvasContext.rect(0, 0, Canvas_width, Canvas_height);
canvasContext.fillStyle = "#000000";
canvasContext.fill();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>