我正在编写一个将图像导入并粘贴到HTML画布中的代码。当我在HTML文件中声明我的<img>
时,该代码有效,但这不允许用户输入新文件。
这是html结构(如果将标记行放回原处,则程序将运行:
<style type='text/css'>
canvas{
border: 10px solid black;
}
</style>
</head>
<body>
<canvas id='balls'>
</canvas>
<canvas id='hide' style:'border: 10px solid black;'>
<!-- <img id="taco" width="300" height="300" src="prime.png"> -->
</canvas>
<div>
<input id='url' placeholder="image url">
<button id='submit'>Submit</button>
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<script src="client.js" async defer></script>
</body>
</html>
这是我正在处理的JS代码的一部分:
$(document).ready(onReady);
var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height= 300;
let bounced = false;
let newPic = `id="taco" width="300" height="300" src="prime.png"`
function onReady(){
$('#submit').on('click', updateImage)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
function updateImage() {
newPic= `id="taco" width="300" height="300" src="${$('#url').val()}" alt="prime.png"`
//console.log(newPic)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
let c, can, ctx, img
function makeCanvas(){
c = canvas.getContext('2d');
can=document.getElementById("hide");
console.log(can)
can.width = 300;
can.height = 300;
ctx=can.getContext("2d");
img=document.getElementById("taco");
ctx.drawImage(img,10,10);
console.log(img)
console.log(ctx.drawImage(img,10,10))
}
将HTML文件中的代码放回原位后,我的img console.log语句相同。
答案 0 :(得分:2)
设置画布时,根本不会加载图像。所以你 ctx.drawImage(img,10,10); 呼叫只是绘制...一个未加载的图像...一组空字节...什么都没有。
因此,您应该首先加载图像。之后,绘图工作将轻松完成。这是一个小代码示例:
var canv, ctx, img;
function setup() {
//Setting up canvas
//Fetching Context
ctx = canv.getContext("2d");
//Now drawing our image
ctx.drawImage(img,10,10);
}
img = new Image();
img.onload = setup; //We'll setup the canvas after the image is fully loaded
img.src = "your/path/or/variable/pointing/to/your/image.ext";
希望有帮助!