<canvas id="myCanvas" width="600" height="300"></canvas>
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp(); //包含整个Canvas应用程序
}
function canvasSupport (e) {
return !!e.getContext;
}
function canvasApp () {
var myCanvas = document.getElementById('myCanvas');
if (!canvasSupport(myCanvas)) {
return;
}
var ctx = myCanvas.getContext('2d');
myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;
myCanvas.addEventListener('mousedown', mouseDown, false);
myCanvas.addEventListener('mouseup', mouseUp, false);
myCanvas.addEventListener('mousemove', mouseMove, false);
var rect = {},
drag = false;
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY ;
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
drawRect("fill");
}
}
function drawRect(style){
if (style==="fill"){
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
if (style==="stroke"){
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}
}
function drawScreen () {
ctx.lineWidth = 10;
ctx.fillStyle = "#f36";
ctx.strokeStyle = '#f36';
ctx.font="24px Arial";
ctx.fillText("拖动鼠标就可以绘制矩形", 50, 50);
}
drawScreen();
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.