我在画布中有一个默认图像。我希望能够在文本输入中粘贴另一个图像源,并在单击按钮时更新img.src。 这是html:
<canvas id="canvas" width="300" height="400"></canvas>
...
<label for="image">Paste the img url here</label>
<input type="text" name="pic" id="image">
<button onclick="updateImg()">Submit img</button>
和javascript:
...
var image = "https://www.whatever.com/image.png";
var img = new Image();
img.src = image;
img.onload = function() {
draw(this);
};
function updateImg() {
image = document.getElementById("image").value;
}
...
我做错了什么?
P.S。抱歉我的英文。
答案 0 :(得分:4)
加载后必须绘制图像。
<canvas id="canvas" width="300" height="400"></canvas>
...
<label for="image">Paste the img url here</label>
<input type="text" name="pic" id="image">
<button onclick="updateImg()">Submit img</button>
<script>
function updateImg() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj,0,0);
};
imageObj.src = document.getElementById("image").value;
}
</script>