Last active
April 23, 2024 16:31
-
-
Save radist2s/5988737 to your computer and use it in GitHub Desktop.
Simple Canvas cliping with anti aliasing by alpha channel of mask image or canvas shape.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas id="show" width="300" height="300"></canvas> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var scratchCropCanvas = null | |
function createCanvas(width, height){ | |
var canvas = document.createElement('canvas'); | |
canvas.width = width || 100; | |
canvas.height = height || 100; | |
return canvas; | |
} | |
function cropRadial(image, width, height){ | |
width = width || 100 | |
height = height || 100 | |
if (!scratchCropCanvas){ | |
scratchCropCanvas = createCanvas(width, height) | |
} | |
else { | |
scratchCropCanvas.width = width | |
scratchCropCanvas.height = height | |
} | |
var canvas = scratchCropCanvas, | |
ctx = canvas.getContext('2d') | |
ctx.drawImage(image, 0, 0) | |
ctx.globalCompositeOperation = 'destination-in' | |
ctx.beginPath() | |
ctx.arc(width/2, width/2, height/2, 0, 2 * Math.PI, true) | |
ctx.fill() | |
return canvas | |
} | |
function maskImage(image, maskImage, width, height){ | |
width = width || maskImage.width | |
height = height || maskImage.height | |
if (!scratchCropCanvas){ | |
scratchCropCanvas = createCanvas(width, height) | |
} | |
else { | |
scratchCropCanvas.width = width | |
scratchCropCanvas.height = height | |
} | |
var canvas = scratchCropCanvas, | |
ctx = canvas.getContext('2d') | |
ctx.drawImage(image, 0, 0) | |
ctx.globalCompositeOperation = 'destination-in' | |
ctx.drawImage(maskImage, 0, 0) | |
return canvas | |
} | |
canvas = document.getElementById("show"); | |
context = canvas.getContext("2d"); | |
var im = new Image(); | |
im.onload = function () { | |
context.beginPath(); | |
context.rect(0, 0, canvas.width, canvas.height); | |
context.fillStyle = 'red'; | |
context.fill(); | |
var cvMask = createCanvas(300, 300), | |
ctxMask = cvMask.getContext('2d') | |
ctxMask.fillStyle = 'blue'; | |
ctxMask.beginPath() | |
ctxMask.arc(cvMask.width/2, cvMask.width/2, cvMask.width/2-10, 0, 2 * Math.PI, true) | |
ctxMask.fill() | |
context.drawImage(maskImage(im, cvMask), 0, 0); | |
//context.drawImage(cropRadial(im, 290, 290), 0, 0); | |
} | |
im.src = "http://placekitten.com/300/300"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment