【发布时间】:2017-01-24 20:09:20
【问题描述】:
我知道这个问题之前已经讨论过,并且我已经阅读了很多文章并尝试了声称有效的方法,所以请不要立即放弃我的问题。
我正在尝试将不同的图像加载到统一大小的画布中。它可以是单个图像或多个图像,但我一次处理一个图像。
这里是主要代码(HTML/JS/PHP):
<?php
if ($record->photo != "") //make the first canvas
{
list($width, $height, $type) = getimagesize($record->photo);
echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
?>
<canvas id="my_canvas" width="341" height = "256"></canvas>
<body>
<script type="text/javascript" src="common.js"></script>
<script type="text/javascript">
var img_src = "<?php echo $record->photo;?>";
var width = "<?php echo $width;?>";
var height = "<?php echo $height;?>";
make_canvas('my_canvas', img_src, width, height);
</script>
<?php
}//if 1
canvas2、3 等的类似块,末尾带有结束标签。
这里是“不知何故”工作的 make_canvas() 函数的版本。这意味着它们有时会在加载时渲染一些图片,但在刷新时可能会有所改善。当要显示多张图片时,我永远无法正常工作。
版本 1 - 不一致并缓存最后一张图片:
function make_canvas(id, src, width, height)
{
if (width > 341)
{
var new_width = 341;
var ratio = new_width / width;
var new_height = Math.round(height * ratio);
}
else
{
var new_width = width;
var new_height = height;
}
document.write("id: " + id + "<br />");
document.write("src: " + src + "<br />");
document.write("new_height: " + new_height + "<br />");
var canvas = document.getElementById(id),
context = canvas.getContext('2d');
base_image = new Image();
//base_image.src = '';
base_image.onload = function(){
context.drawImage(base_image,0,0,new_width, new_height);
}
base_image.src = src;
}
第 2 版:可能会加载一张图片并在刷新时将其缓存
function make_canvas2(id, src, width, height)
{
if (width > 341)
{
var new_width = 341;
var ratio = new_width / width;
var new_height = Math.round(height * ratio);
}
else
{
var new_width = width;
var new_height = height;
}
document.write("id: " + id + "<br />");
document.write("src: " + src + "<br />");
document.write("new_height: " + new_height + "<br />");
var canvas = document.getElementById(id),
context = canvas.getContext('2d');
base_image = new Image();
base_image.src = '';
base_image.addEventListener("load", function() {
// execute drawImage statements here
context.drawImage(base_image,0,0,new_width, new_height);
}, false);
//base_image.onload = function(){ };
base_image.src = src;
}
我尝试在 IF 条件下添加 base_image.complete 以进行 onload 或 onload 函数中的 WHILE 循环,但在第一次加载时无法正确显示多个图像。 我将不胜感激任何工作示例,最好类似于上面并且没有 jQuery。
【问题讨论】:
标签: javascript html image canvas