0
我有一個用戶繪製的畫布。點擊一個按鈕後,我會在第二個畫布中做一些操作,例如修剪掉空白區域並重新對中圖形(以免影響原始畫布)。調整圖像大小而不影響原始畫布的外觀?
我還創建了第三個畫布,以便可以將輸出大小調整爲特定大小。我的問題是,我不希望用戶繪製的原始畫布受到影響。現在一切正常,我的圖像被調整大小,但原始畫布也是如此。如何讓原始畫布不受影響?
這裏是我的功能:
//Get Canvas
c = document.getElementById('simple_sketch');
//Define Context
var ctx = c.getContext('2d');
//Create Copy of Canvas
var copyOfContext = document.createElement('canvas').getContext('2d');
//Get Pixels
var pixels = ctx.getImageData(0, 0, c.width, c.height);
//Get Length of Pixels
var lengthOfPixels = pixels.data.length;
//Define Placeholder Variables
var i;
var x;
var y;
var bound = {
top: null,
left: null,
right: null,
bottom: null
};
//Loop Through Pixels
for (i = 0; i < lengthOfPixels; i += 4) {
if (pixels.data[i+3] !== 0) {
x = (i/4) % c.width;
y = ~~((i/4)/c.width);
if (bound.top === null) {
bound.top = y;
}
if (bound.left === null) {
bound.left = x;
} else if (x < bound.left) {
bound.left = x;
}
if (bound.right === null) {
bound.right = x;
} else if (bound.right < x) {
bound.right = x;
}
if (bound.bottom === null) {
bound.bottom = y;
} else if (bound.bottom < y) {
bound.bottom = y;
}
}
}
//Calculate Trimmed Dimensions
var padding = 1;
var trimmedHeight = bound.bottom + padding - bound.top;
var trimmedWidth = bound.right + padding - bound.left;
//Get Longest Dimension (We Need a Square Image That Fits the Drawing)
var longestDimension = Math.max(trimmedHeight, trimmedWidth);
//Define Rect
var trimmedRect = ctx.getImageData(bound.left, bound.top, trimmedWidth, trimmedHeight);
//Define New Canvas Parameters
copyOfContext.canvas.width = longestDimension;
copyOfContext.canvas.height = longestDimension;
copyOfContext.putImageData(trimmedRect, (longestDimension - trimmedWidth)/2, (longestDimension - trimmedHeight)/2);
copyOfContext.globalCompositeOperation = "source-out";
copyOfContext.fillStyle = "#fff";
copyOfContext.fillRect(0, 0, longestDimension, longestDimension);
//Define Resized Context
var resizedContext = c.getContext('2d');
resizedContext.canvas.width = 32;
resizedContext.canvas.height = 32;
resizedContext.drawImage(copyOfContext.canvas, 0, 0, 32, 32);
//Get Cropped Image URL
var croppedImageURL = resizedContext.canvas.toDataURL("image/jpeg");
//Open Image in New Window
window.open(croppedImageURL, '_blank');
我看到你明白,帆布#1可以是畫布#2的drawImage源。你爲什麼不製作你不想影響的畫布副本? – markE
我試圖通過設置resizedContext等於copyOfContext,但它輸出一個完全黑色的圖像。 – KingPolygon