以下带有 3 个画布的代码可以完美地与最新的 IE 和 Mozilla FireFox 配合使用。第三个画布 (#drawingSurface3) 在 Google Chrome 上失败,开发者控制台中没有任何错误。连线条都没有画出来。
<!doctype html>
<html>
<head>
<title>Drawing lines in Canvas</title>
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="drawingSurface" width="300" height="300">
<p>Your browser does not support the canvas element.</p>
</canvas>
<br />
<canvas id="drawingSurface2" width="300" height="300">
<p>Your browser does not support the canvas element.</p>
</canvas>
<br />
<canvas id="drawingSurface3" width="300" height="300">
<p>Your browser does not support the canvas element.</p>
</canvas>
<script src="scripts/modernzr 2-6-2.js"></script>
<script src="scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var canvas = document.getElementById("drawingSurface");
var ctx;
if (ctx = canvas.getContext("2d")) {
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(75, 100);
ctx.lineTo(25, 100);
// ctx.stroke();
ctx.closePath();
ctx.stroke();
// ctx.fill();
}
var canvas2 = document.getElementById("drawingSurface2");
if (canvas2 && (ctx = canvas2.getContext("2d"))) {
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(100, 300);
ctx.lineTo(150, 300);
ctx.lineTo(150, 155);
ctx.lineTo(205, 155);
ctx.lineTo(205, 100);
ctx.closePath();
ctx.fillStyle = "#0099ff";
ctx.fill();
ctx.lineWidth = 6;
ctx.lineJoin = "round";
ctx.strokeStyle = "#cccccc";
ctx.stroke();
}
var canvas3 = document.getElementById("drawingSurface3");
if (canvas3 && (ctx = canvas3.getContext("2d"))) {
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
//alert(ctx.getImageData());
ctx.beginPath();
ctx.moveTo(100, 125);
ctx.lineTo(150, 285);
ctx.lineTo(200, 233);
ctx.lineTo(250, 368);
ctx.lineTo(300, 402);
ctx.lineTo(350, 300);
ctx.lineTo(400, 90);
//ctx.closePath();
ctx.stroke();
};
img.src = "images/chartBackground.png";
}
});
</script>
</body>
</html>