我在Javascript / jQuery中创建了一些可以拍摄图像的东西,并将其重建为一个多维数组。由于用户可以上传自己的图像,我需要动态获取图像尺寸,并使用它们相应地缩放画布,然后绘制图像。
唯一的问题是,缩放画布,然后绘制到它的过程显然让我失望。现在正在发生的事情是画布正在缩放到图像大小,但是画布的画布的尺寸都被打破了。
希望有人能给我一些见解!
HTML
<div class="canvas">
<canvas id="myCanvas" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</div>
<div class="options">
<input type='file' id="imgInp" />
</div>
<div id="status">
<h1>Image to Multidimensional Array</h1>
<p>What this does it pretty much self explanatory, it turns any uploaded image into a multidimensional array.
<br/>The array is structured so that for every array inside the main array is a Y coord. Every bit of data inside of that Y array is an X coord.</p>
<h2>Output</h2>
<br>
<p>
<span id="statusout" onClick="this.select();"></span>
</p>
</div>
JAVASCRIPT
function loadCanvas(dataURL, width, height) {
$('#myCanvas').css({
width: width,
height: height
});
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
// load image from data url
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 0, 0);
var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
var datalocation;
var datalocationhex;
var coord;
for (var y = 0; y < canvas.height; y++) {
$('#statusout').append("[");
for (var x = 0; x < canvas.width; x++) {
datalocation = context.getImageData(x, y, 1, 1).data;
datalocationhex = "#" + ("000000" + rgbToHex(datalocation[0], datalocation[1], datalocation[2])).slice(-6);
coord = "x=" + x + ", y=" + y;
if (x == 0) {
$('#statusout').append("'" + datalocationhex + "'");
} else {
$('#statusout').append(",'" + datalocationhex + "'");
}
}
if (y == canvas.height) {
$('#statusout').append("]<br>");
} else {
$('#statusout').append("],<br>");
}
}
};
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
imageObj.src = dataURL;
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
if (img.complete) { // was cached
var width = img.width;
var height = img.height;
loadCanvas(e.target.result, width, height);
} else { // wait for decoding
img.onload = function() {
var width = img.width;
var height = img.height;
loadCanvas(e.target.result, width, height);
}
}
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
});
所以,是的,这就是我所拥有的。 非常感谢您提前提供任何帮助!
修改 这是一个link to the project on CodePen,可以更好地了解事物。
编辑v2 看起来画布有点混乱。多维数组正在吐出精细 - 好吧,有点。它将为图像喷出正确的代码,然后是一堆额外的空白点。因此,画布抽奖仍然存在问题。
答案 0 :(得分:0)
事实证明,在绘制画布时,Canvas元素只会侦听width和height属性,而不是CSS规则。
这是我改变的:
window.onLoad;
变成了这个:
function fn_load(){
// Your statements
}