使用Javascript以编程方式剪辑/剪切图像 [英] Programmatically Clip/Cut image using Javascript
问题描述
是否有关于如何剪切或剪切大图像的文档/教程,以便用户只能看到此图像的一小部分?假设源图像是10帧动画,端到端堆叠,因此它非常宽。我怎么能用Javascript一次只显示1个任意帧的动画?
Are there any documents/tutorials on how to clip or cut a large image so that the user only sees a small portion of this image? Let's say the source image is 10 frames of animation, stacked end-on-end so that it's really wide. What could I do with Javascript to only display 1 arbitrary frame of animation at a time?
我已经研究了这个CSS Spriting技术,但我不认为我可以在这里使用它。源图像是从服务器动态生成的;在从服务器返回之前,我不知道每个帧的总长度或大小。我希望我可以这样做:
I've looked into this "CSS Spriting" technique but I don't think I can use that here. The source image is produced dynamically from the server; I won't know the total length, or the size of each frame, until it comes back from the server. I'm hoping that I can do something like:
var image = getElementByID('some-id');
image.src = pathToReallyLongImage;
// Any way to do this?!
image.width = cellWidth;
image.offset = cellWidth * imageNumber;
推荐答案
这可以通过将图像封闭在视口div。在div上设置宽度和高度(根据您的需要),然后设置 position:relative
和 overflow:hidden
在上面。绝对将图像放在其中并更改位置以更改显示的部分。
This can be done by enclosing your image in a "viewport" div. Set a width and height on the div (according to your needs), then set position: relative
and overflow: hidden
on it. Absolutely position your image inside of it and change the position to change which portions are displayed.
显示从(10,20)开始的图像的30x40部分:
To display a 30x40 section of an image starting at (10,20):
<style type="text/css">
div.viewport {
overflow: hidden;
position: relative;
}
img.clipped {
display: block;
position: absolute;
}
</style>
<script type="text/javascript">
function setViewport(img, x, y, width, height) {
img.style.left = "-" + x + "px";
img.style.top = "-" + y + "px";
if (width !== undefined) {
img.parentNode.style.width = width + "px";
img.parentNode.style.height = height + "px";
}
}
setViewport(document.getElementsByTagName("img")[0], 10, 20, 30, 40);
</script>
<div class="viewport">
<img class="clipped" src="/images/clipped.png" alt="Clipped image"/>
</div>
常见的CSS属性与类相关联,因此您可以在页面上拥有多个视口/剪裁图像。可以随时调用 setViewport(...)
函数来更改图像的显示部分。
The common CSS properties are associated with classes so that you can have multiple viewports / clipped images on your page. The setViewport(…)
function can be called at any time to change what part of the image is displayed.
这篇关于使用Javascript以编程方式剪辑/剪切图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!