如何根据图片大小设置html5 camvas的图像宽度和高度?
我有以下代码 它从数据库中获取一些base64编码的图片,并将其显示在html5画布的屏幕上如何根据图片大小设置html5 camvas的图像宽度和高度?,html,canvas,Html,Canvas,我有以下代码 它从数据库中获取一些base64编码的图片,并将其显示在html5画布的屏幕上 <?php $sql = "SELECT * FROM editor_picture"; $rs = $db->GetAssoc($sql); //Getting the result in an array $rs_array = array_values($rs); $count_files = count($rs_array); ?> `<script type="te
<?php
$sql = "SELECT * FROM editor_picture";
$rs = $db->GetAssoc($sql); //Getting the result in an array
$rs_array = array_values($rs);
$count_files = count($rs_array);
?>
`<script type="text/javascript">
<?php for ($x = 0; $x < $count_files; $x++) { ?>
var canvas<?php echo $x; ?> = document.getElementById('canvas<?php echo $x; ?>');
var context<?php echo $x; ?> = canvas<?php echo $x; ?>.getContext('2d');
var img<?php echo $x; ?> = new Image();
img<?php echo $x; ?>.onload = function () {
context<?php echo $x; ?>.drawImage(this, 0, 0, img<?php echo $x; ?>.width, img<?php echo $x; ?>.height);
}
//$rs_array[$x]['editor_picture_use_base64'] contains the base64 encoded string
img<?php echo $x; ?>.src = "<?php echo str_replace(' ', '+', $rs_array[$x]['editor_picture_use_base64']); ?>";
<?php } ?>
</script>
<?php
for ($x = 0; $x < $count_files; $x++) {
?>
<canvas id="canvas<?php echo $x; ?>" width="" height=""></canvas>
<?php
}
?>
`
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var img=新图像();
img.onload=函数(){
context.drawImage(this,0,0,img.width,img.height);
}
//$rs\U数组[$x]['editor\u picture\u use\u base64']包含base64编码字符串
img.src=“”;
只需在加载图像时,但在绘制之前设置画布的大小
您需要使用natural*size,因为它反映了图像的实际位图大小:
img<?php echo $x; ?>.onload = function () {
var canvas = context<?php echo $x; ?>.canvas;
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
context<?php echo $x; ?>.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight);
}
img.onload=函数(){
var canvas=context.canvas;
canvas.width=this.naturalWidth;
canvas.height=this.naturalHeight;
drawImage(this,0,0,this.naturalWidth,this.naturalHeight);
}
最后一个参数实际上是不必要的,您可以改为:
context<?php echo $x; ?>.drawImage(this, 0, 0);
context.drawImage(this,0,0);
@BoS.Petersen没问题!