摘要:HTML5 canvas magnifying glass (放大鏡) sample code Part1
原本看到 Feature #2: The Clipping Region 的文章(如下),以為已經到正解
但是他少加了
clearRect與最重要的
context.save();//儲存狀態
context.restore();//回復狀態
所以他的程式只可以跑一次
Complete Magnifying Glass Source Code: https://skydrive.live.com/embed?cid=FBEB6373D9321A7F&resid=FBEB6373D9321A7F%2124088&authkey=AKfEacPDiHfmMXo
這三點我是看 HTML5 Canvas Clipping Region Tutorial 獲得的靈感。
function drawScreen() {
context.save();
context.clearRect(0, 0, theCanvas.width, theCanvas.height);
context.drawImage(oneImage, 0, 0, theCanvas.width, theCanvas.height);
context.beginPath();
context.arc(magnifyingGlassX, magnifyingGlassY,
magnifyingGlassRadius, 0, Math.PI * 2, false);
context.clip();
context.drawImage(theCanvas,
magnifyRectangle.x, magnifyRectangle.y,
magnifyRectangle.width, magnifyRectangle.height,
magnifyRectangle.x + magnifyRectangle.width / 2 -
scaledMagnifyRectangle.width / 2,
magnifyRectangle.y + magnifyRectangle.height / 2 -
scaledMagnifyRectangle.height / 2,
scaledMagnifyRectangle.width,
scaledMagnifyRectangle.height);
context.restore();
其他的Javascript
var theCanvas;
var context;
var oneImage;
var magnifyingGlassRadius = 200;
var magnifyingGlassX = 400;
var magnifyingGlassY = 300;
var magnifyRectangle = { x: 200, y: 100, width: 400, height: 400 };
var scaledMagnifyRectangle = { width: 800, height: 800 };
window.onload = function () {
theCanvas = document.getElementById("canvasDicom0");
context = theCanvas.getContext("2d");
theCanvas.addEventListener('mousemove', mousemove, false);
oneImage = new Image();
oneImage.src = "Images/Tulips.jpg";
oneImage.onload = function () {
drawScreen();
}
}
function mousemove(event) {
var x = event.offsetX;
var y = event.offsetY;
magnifyingGlassX=x;
magnifyingGlassY=y;
magnifyRectangle.x = magnifyingGlassX - magnifyingGlassRadius;
magnifyRectangle.y = magnifyingGlassY - magnifyingGlassRadius;
if (magnifyRectangle.x < 0) {
magnifyRectangle.x = 0;
}
if (magnifyRectangle.y < 0) {
magnifyRectangle.y = 0;
}
magnifyRectangle.width = 2 * magnifyingGlassRadius;
magnifyRectangle.height = 2 * magnifyingGlassRadius;
//Debug.writeln("magnifyingGlassX=" + magnifyingGlassX);
//Debug.writeln("magnifyingGlassY=" + magnifyingGlassY);
drawScreen();
}
UI 用Canvas
<canvas id="canvasDicom0" width="1024" height="768"></canvas>
See Also: HTML5 canvas magnifying glass (放大鏡) sample code Part2