我想用php显示图像并使用canvas + jquery旋转该图像。问题是当单个图像都运行良好时。但当imgae显示多个时,旋转失败。我知道问题是图像ID或javascript上的画布ID,但我无法解决这个问题。你能救我吗?
这是我的PHP代码:
while($data = mysql_fetch_array($aksi)):?>
<div>
<img src="image/<?php echo $data['dir']; ?>" alt="" id="image" />
<canvas id="canvas"></canvas>
</div>
<p>
<strong>Rotate Image: </strong>
<a href="javascript:;" id="resetImage">Reset Image</a>
<a href="javascript:;" id="rotate90">90°</a>
<a href="javascript:;" id="rotate180">180°</a>
<a href="javascript:;" id="rotate270">270°</a>
</p>
<?php
$no++;
endwhile;
?>
这里是javascript代码:
<script type="text/javascript">
var img = null, canvas = null;
$(document).ready(function(){
// Initialize image and canvas
img = document.getElementById('image');
canvas = document.getElementById('canvas');
if(!canvas || !canvas.getContext){
canvas.parentNode.removeChild(canvas);
} else {
img.style.position = 'absolute';
img.style.visibility = 'hidden';
}
rotateImage(0);
// Handle clicks for control links
$('#resetImage').click(function(){ rotateImage(0); });
$('#rotate90').click(function(){ rotateImage(90); });
$('#rotate180').click(function(){ rotateImage(180); });
$('#rotate270').click(function(){ rotateImage(270); });
});
function rotateImage(degree)
{
if(document.getElementById('canvas')){
var cContext = canvas.getContext('2d');
var cw = img.width, ch = img.height, cx = 0, cy = 0;
// Calculate new canvas size and x/y coorditates for image
switch(degree){
case 90:
cw = img.height;
ch = img.width;
cy = img.height * (-1);
break;
case 180:
cx = img.width * (-1);
cy = img.height * (-1);
break;
case 270:
cw = img.height;
ch = img.width;
cx = img.width * (-1);
break;
}
// Rotate image
canvas.setAttribute('width', cw);
canvas.setAttribute('height', ch);
cContext.rotate(degree * Math.PI / 180);
cContext.drawImage(img, cx, cy);
} else {
// Use DXImageTransform.Microsoft.BasicImage filter for MSIE
switch(degree){
case 0: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)'; break;
case 90: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)'; break;
case 180: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)'; break;
case 270: image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)'; break;
}
}
}
答案 0 :(得分:0)
我的事...... 不要将ID标签用于重复多次的项目。更改为Class标签并在之后给我打电话;)
我最好的!