離屏Canvas——製作放大鏡效果
阿新 • • 發佈:2019-02-19
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body style="background: black;"> <canvas id="canvas" style="display:block;margin:0 auto;border:1px solid #aaa;"> 您的瀏覽器尚不支援canvas </canvas> <canvas id="offCanvas" style="display: none"> </canvas> <script> var canvas = document.getElementById("canvas") var context = canvas.getContext("2d") var offCanvas = document.getElementById("offCanvas") var offContext = offCanvas.getContext("2d") var image = new Image() var isMouseDown = false var scale window.onload = function(){ canvas.width = 1152 canvas.height = 768 image.src = "img-lg.jpg" image.onload = function(){ offCanvas.width = image.width offCanvas.height = image.height scale = offCanvas.width / canvas.width context.drawImage( image , 0 , 0 , canvas.width , canvas.height ) offContext.drawImage( image , 0 , 0 ) } } function windowToCanvas( x , y ){ var bbox = canvas.getBoundingClientRect() return {x:x-bbox.left , y:y-bbox.top} } canvas.onmousedown = function(e){ e.preventDefault() isMouseDown = true point = windowToCanvas( e.clientX , e.clientY ) console.log( point.x , point.y ) drawCanvasWithMagnifier( true , point ) } canvas.onmouseup = function(e){ e.preventDefault() isMouseDown = false drawCanvasWithMagnifier( false ) } canvas.onmouseout = function(e){ e.preventDefault() isMouseDown = false drawCanvasWithMagnifier( false ) } canvas.onmousemove = function(e){ e.preventDefault() if( isMouseDown == true ){ point = windowToCanvas( e.clientX , e.clientY ) console.log( point.x , point.y ) drawCanvasWithMagnifier( true , point ) } } function drawCanvasWithMagnifier( isShowMagnifier , point ){ context.clearRect( 0 , 0 , canvas.width , canvas.height ) context.drawImage( image , 0 , 0 , canvas.width , canvas.height ) if( isShowMagnifier == true ){ drawMagnifier( point ) } } function drawMagnifier( point ){ var mr = 200 var imageLG_cx = point.x * scale var imageLG_cy = point.y * scale var sx = imageLG_cx - mr var sy = imageLG_cy - mr var dx = point.x - mr var dy = point.y - mr context.save() context.lineWidth = 10.0 context.strokeStyle = "#069" context.beginPath() context.arc( point.x , point.y , mr , 0 , Math.PI*2 , false ) context.stroke() context.clip() context.drawImage( offCanvas , sx , sy , 2*mr , 2*mr , dx , dy , 2*mr , 2*mr ) context.restore() } </script> </body> </html>
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
引數值
引數 | 描述 |
---|---|
img | 規定要使用的影象、畫布或視訊。 |
sx | 可選。開始剪下的 x 座標位置。 |
sy | 可選。開始剪下的 y 座標位置。 |
swidth | 可選。被剪下影象的寬度。 |
sheight | 可選。被剪下影象的高度。 |
x | 在畫布上放置影象的 x 座標位置。 |
y | 在畫布上放置影象的 y 座標位置。 |
width | 可選。要使用的影象的寬度。(伸展或縮小影象) |
height | 可選。要使用的影象的高度。(伸展或縮小影象) |