• 0
Sign in to follow this  
fiote

"Crop" images

Question

Esse código extende o objeto Image possibilitando o uso do método crop(). O método crop permite definir um retângulo dentro da figura a ser exibido.

Image.prototype.crop = function(x,y,lenx,leny) {    
    if (!this.divWrapper) {
        this.divWrapper = document.createElement('div');
        this.divWrapper.style.position = 'relative';
        this.divWrapper.style.overflow = 'hidden';
        this.parentNode.appendChild(this.divWrapper);
        this.divWrapper.appendChild(this);
        this.style.position = 'absolute';
    }
    this.divWrapper.style.width = lenx;
    this.divWrapper.style.height = leny;
    this.style.left = x*-1;
    this.style.top = y*-1;
    return this;
}


Os argumentos x,y definem o canto "superior-esquerdo" do retângulo.
lenx é a largura do retângulo (indo pra direita da posição x,y).
leny é a altura do retângulo (indo para baixo da posição x,y).

CODE
. lenx
(x,y) ---------- >
|
|
| leny
|
v



Segue abaixo um exemplo, utilizando a imagem-logo aqui do scriptBrasil:

<table>
    <tr valign='top'>
        <td>Imagem Original</td>
        <td>Imagem "cropada"</td>
    </tr>
    <tr>
        <td id='divImg1'></td>
        <td id='divImg2'></td>        
    </tr>
</table>

<script>

Image.prototype.crop = function(x,y,lenx,leny) {    
    if (!this.divWrapper) {
        this.divWrapper = document.createElement('div');
        this.divWrapper.style.position = 'relative';
        this.divWrapper.style.overflow = 'hidden';
        this.parentNode.appendChild(this.divWrapper);
        this.divWrapper.appendChild(this);
        this.style.position = 'absolute';
    }
    this.divWrapper.style.width = lenx;
    this.divWrapper.style.height = leny;
    this.style.left = x*-1;
    this.style.top = y*-1;
    return this;
}

var img1 = new Image();
img1.src = 'http://scriptbrasil.com.br/forum/style_images/sb_images/logo4.jpg';
document.getElementById('divImg1').appendChild(img1);

var img2 = new Image();
img2.src = 'http://scriptbrasil.com.br/forum/style_images/sb_images/logo4.jpg';
document.getElementById('divImg2').appendChild(img2);

img2.crop(70,0,210,50);

</script>
Edited by fiote

Share this post


Link to post
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this