我使用的jQuery版本是2.1.1、網頁是HTML5,在取得canvas物件時,卻沒有反應。
原來在jQuery取得canvas物件需要有一點「眉角」
Javascript的語法如下:
var canvas = document.getElementById('canvasTEST');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.fillStyle = "#0000FF";
ctx.fillRect(10,50,100,100);
canvas.addEventListener( "mousedown", mouseDown );
function mouseDown() {
ctx.beginPath();
ctx.strokeStyle = "#00FF00";
ctx.lineWidth = 10;
ctx.moveTo(10,10);
ctx.lineTo(50,200);
ctx.stroke();
}
JQuery的語法如下:
var $canvas = $('#canvasTEST');
var ctx = $canvas[0].getContext('2d');
ctx.beginPath();
ctx.fillStyle = "#0000FF";
ctx.fillRect(10,50,100,100);
$canvas.mousedown(function (e) {
ctx.beginPath();
ctx.strokeStyle = "#00FF00";
ctx.lineWidth = 10;
ctx.moveTo(10,10);
ctx.lineTo(50,200);
ctx.stroke();
});
兩者的差異在此:
var ctx = canvas.getContext('2d');
var ctx = $canvas[0].getContext('2d');
網路上有人解釋如下:
Because getContext('2d') works on DOM element,
where var 「$canvas = $('#canvas1');」return a jQuery object but node a DOM element.
And to retrieve a DOM element from jQuery object you need to use $canvas[0].
完整的HTML5語法如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TESTING</title>
</head>
<body>
<canvas id="canvas1" width="300" height="300" style="border: 2px solid #999900" />
</body>
</html>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script>
var $canvas = $('#canvasTEST');
var ctx = $canvas[0].getContext('2d');
ctx.beginPath();
ctx.fillStyle = "#0000FF";
ctx.fillRect(10,50,100,100);
$canvas.mousedown(function (e) {
ctx.beginPath();
ctx.strokeStyle = "#00FF00";
ctx.lineWidth = 10;
ctx.moveTo(10,10);
ctx.lineTo(50,200);
ctx.stroke();
});
</script>